<template>
  <el-dialog v-model="show"
             title="设置 - 菜单/权限"
             width="500"
             :draggable="true"
             :close-on-click-modal="false"
             node-key="id">
    <el-alert title="说明" type="info" show-icon :closable="false" class="m-b-5">
      <template #default>
        <el-row class="m-b-5">1. 选择子和选择父无关，如果不选择父，选择子中的任何东西时因为父看不到，所以所有的子也看不到，即使设置也无用</el-row>
        <el-row>2. 看效果，请重新登录，刷新页面</el-row>
      </template>
    </el-alert>
    <el-tree
        ref="treeRef"
        :data="menus"
        show-checkbox
        node-key="id"
        :check-strictly="true"
        :props="defaultProps"/>
    <template #footer>
      <el-button @click="hideComp" style="padding: 0 20px" v-if="!loading">
        <span class="iconfont iaiai-close f20 m-r-5"></span>
        取消
      </el-button>
      <el-button type="primary" style="padding: 0 20px" :loading="loading" @click="edit" plain>
        <span class="iconfont iaiai-correct f20 m-r-5" v-if="!loading"></span>
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {ref, defineExpose, defineEmits, inject} from "vue"
import {FormInstance, FormRules} from "element-plus"

const $api = inject('$api')
const $post = inject('$post')
const $toast = inject('$toast')
const emit = defineEmits(['onsuccess'])
const show = ref(false)
const loading = ref(false)
const menus = ref([])
const roleId = ref("")   //id

const defaultProps = {
  children: 'children',
  label: 'title',
}

const treeRef = ref()

function edit(){
  //返回值包含半选中节点数据
  var selectNodes = treeRef.value!.getCheckedNodes()
  var menuIds = []

  if(selectNodes!=null && selectNodes.length>0){
    for(var i=0;i<selectNodes.length;i++){
      menuIds.push(selectNodes[i].id)
    }
  }

  $post($api.roleMenuEdit,{id:roleId.value,menuIds:menuIds}).then((res:any)=>{
    show.value = false
    $toast.success('保存成功')
  })
}

function showComp(id:any){
  show.value = true
  roleId.value = id

  $post($api.roleMenu,{id:id}).then((res:any)=>{
    menus.value = res.data["result"].menus

    treeRef.value!.setCheckedKeys(res.data["result"].menuIds)
  })
}
function hideComp(){
  show.value = false
}

defineExpose({
  showComp,
})
</script>

<style lang="scss" scoped>

</style>
